package com.qm.console.component.util;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by a8_1 on 2018/8/3.
 */
public class IdGenerator {

    private static final AtomicInteger SERIAL = new AtomicInteger(0);

    /**
     * timestamp to 2100-01-01 is 4102416000000, < (1 << 42)
     * Rule:
     * |<-- 45 bit -->|<-- 8 bit -->|<-- 10 bit -->|
     * |  time second |  server id   | atomic byte |
     *
     * @param type
     * @return unique id
     */
    public static Long generate(int type) {
        Long now = System.currentTimeMillis();
        int typeId = type;
        int num = SERIAL.incrementAndGet();
        if (num >= (1 << 10)) {
            SERIAL.set(0);
        }
        Long id = (now << 18)
                + (typeId << 10)
                + num;
        return id;
    }

    public static String generateOrderId(int type){
        return type + generate(type).toString();
    }
}
